package com.waa.gulimallseckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.waa.gulimall.common.to.mq.SeckilOrderTo;
import com.waa.gulimall.common.utils.R;
import com.waa.gulimall.common.vo.MemberRespVo;
import com.waa.gulimallseckill.feign.CouponFeignServie;
import com.waa.gulimallseckill.feign.ProductFeignService;
import com.waa.gulimallseckill.interceptor.LoginUserInterceptor;
import com.waa.gulimallseckill.service.SeckillService;
import com.waa.gulimallseckill.to.SeckillSkuRedisTo;
import com.waa.gulimallseckill.vo.SeckillSessionsWithSkus;
import com.waa.gulimallseckill.vo.SeckillSkuVo;
import com.waa.gulimallseckill.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignServie couponFeignServie;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1.扫描最近三天需要参与秒杀的活动
        final R session = couponFeignServie.getLates3DaySession();
        if (session.getCode() == 0) {
            //上架商品
            final List<SeckillSessionsWithSkus> sessionData = (List<SeckillSessionsWithSkus>) session.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //缓存到redis
            //1.缓存活动信息
            saveSessionInfos(sessionData);
            //2.缓存活动的关联商品信息
            saveSessionSkuInfos(sessionData);
        }
    }

    @Override
    /**
     * 返回当前可以参与秒杀的信息
     */
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //确定当前时间属于那个秒杀场次
        final long time = new Date().getTime();
        final Set<String> keys = stringRedisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            final String[] split = key.replace(SESSIONS_CACHE_PREFIX, "").split("_");
            final long start = Long.parseLong(split[0]);
            final long end = Long.parseLong(split[2]);
            if (time >= start && time <= end) {
                //获取这个秒杀场次需要的所有商品信息
                final List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);
                final BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                final List<String> list = hashOps.multiGet(range);
                if (list != null && list.size() != 0) {
                    final List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        final SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(item.toString(), SeckillSkuRedisTo.class);
                        return seckillSkuRedisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;


            }

        }
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckilInfo(Long skuId) {
        //找到所有需要参与秒杀的商品的key
        final BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        final Set<String> keys = hashOps.keys();
        if (keys.size() > 0 && keys != null) {
            String regx = "//d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    final String json = hashOps.get(key);
                    final SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    //随机码
                    final long current = new Date().getTime();
                    if (current >= seckillSkuRedisTo.getStartTime() && current <= seckillSkuRedisTo.getEndTime()) {

                    } else {
                        seckillSkuRedisTo.setRandomCode(null);
                    }
                    return seckillSkuRedisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        final MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        final BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        final String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            final SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //校验合法性
            //1.时间
            final Long startTime = seckillSkuRedisTo.getStartTime();
            final Long endTime = seckillSkuRedisTo.getEndTime();
            final long current = new Date().getTime();
            long ttl = endTime - startTime;
            if (current >= startTime && current <= endTime) {//
                //2.校验随机吗和商品id
                final String randomCode = seckillSkuRedisTo.getRandomCode();
                String skuId = seckillSkuRedisTo.getPromotionSessionId() + "_" + seckillSkuRedisTo.getSkuId();

                if (randomCode.equals(key) && killId.equals(skuId)) {
                    //3.验证购物数量是否合理
                    final String seckillLimit = seckillSkuRedisTo.getSeckillLimit() + "";
                    if (num <= Integer.parseInt(seckillLimit)) {
                        //验证此人是否已经买过。幂等性，如果秒杀成功过，就去redis中占位
                        final String redisKey = memberRespVo.getId() + "_" + skuId;
                        //自动过期
                        final Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);//是否买过，买过就不占了
                        if (aBoolean) {
                            //占位成功说明从来都没有买过
                            final RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            try {
//                                final boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                final boolean b = semaphore.tryAcquire(num);//拿不到就直接走，不用等待
                                if (b){
                                    //秒杀成功
                                    //快速下单，发送mq消息
                                    final String orderSn = UUID.randomUUID().toString().replace("-", "");
                                    final SeckilOrderTo seckilOrderTo = new SeckilOrderTo();
                                    seckilOrderTo.setOrderSn(orderSn);
                                    seckilOrderTo.setMemberId(memberRespVo.getId());
                                    seckilOrderTo.setNum(num);
                                    seckilOrderTo.setPromotionSessionId(seckillSkuRedisTo.getPromotionSessionId());
                                    seckilOrderTo.setSkuId(seckillSkuRedisTo.getSkuId());
                                    seckilOrderTo.setSeckillPrice(seckilOrderTo.getSeckillPrice());
                                    rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckilOrderTo);

                                    return orderSn;
                                }
                                return  null;
                            } catch (Exception e) {
                                return null;
                            }
                        }
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }

        }

        return null;
    }

    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessionData) {
        sessionData.stream().forEach(session -> {
            //准备hash操作
            final BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                //商品的随机码
                final String token = UUID.randomUUID().toString().replace("_", "");
                if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString())) {
                    //缓存商品
                    final SeckillSkuRedisTo skuRedisTo = new SeckillSkuRedisTo();
                    //1.sku的基本数据
                    final R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        final SkuInfoVo infoVo = (SkuInfoVo) skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        skuRedisTo.setSkuInfo(infoVo);
                    }
                    //2.sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, skuRedisTo);
                    //3.设置上当前商品的秒杀时间信息
                    skuRedisTo.setStartTime(session.getStartTime().getTime());
                    skuRedisTo.setEndTime(session.getEndTime().getTime());

                    skuRedisTo.setRandomCode(token);


                    String s = JSON.toJSONString(skuRedisTo);
                    ops.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(), s);
                    //如果当前这个场次的商品的库存信息已经上架就不需要上架
                    //使用库存作为分布式信号量 限流
                    final RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品的秒杀件数可以作为信号量
                    semaphore.trySetPermits(Integer.parseInt(String.valueOf(seckillSkuVo.getSeckillCount())));
                }


            });
        });
    }

    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessionData) {
        sessionData.stream().forEach(session -> {
            final long startTime = session.getStartTime().getTime();
            final long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            final List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
            //缓存活动信息
            final Boolean hasKey = stringRedisTemplate.hasKey(key);
            if (!hasKey) {
                stringRedisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }
}
